package com.mou.controller.admin;

import com.mou.annotation.Log;
import com.mou.constant.JwtClaimsConstant;
import com.mou.dto.UserDTO;
import com.mou.dto.UserLoginDTO;
import com.mou.dto.UserPageQueryDTO;
import com.mou.entity.User;
import com.mou.properties.JwtProperties;
import com.mou.result.PageResult;
import com.mou.result.Result;
import com.mou.service.UserService;
import com.mou.utils.JwtUtil;
import com.mou.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RequestMapping("/admin/user")
@RestController("adminUserController")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("user:{}",userLoginDTO);
        User user = userService.adminLogin(userLoginDTO);
        Map<String,Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getSecretKey(),
                jwtProperties.getTtl(),
                claims);
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .nickname(user.getNickname())
                .roleId(user.getRoleId())
                .avatar(user.getAvatar())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }
    @Log
    @PostMapping("/register")
    public Result<String> register(@RequestBody UserDTO userDTO){
        log.info("user:{}",userDTO);
        userService.add(userDTO);
        return Result.success();
    }


    @GetMapping("/page")
    public Result<PageResult> page(UserPageQueryDTO userPageQueryDTO){
        log.info("用户分页查询:{}", userPageQueryDTO);
        PageResult pageResult = userService.pageQuery(userPageQueryDTO);
        return Result.success(pageResult);
    }

    @Log
    @PutMapping("/delete/{ids}")
    public Result<String> deleted(@PathVariable("ids") List<Integer> ids){
        log.info("用户删除:{}", ids);
        for(Integer id :ids){
            userService.removeById(id);
        }
        return Result.success();
    }

    @Log
    @PutMapping("/update")
    public Result<String> update(@RequestBody UserDTO userDTO){
        log.info("用户修改:{}", userDTO);
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);
        userService.updateProfile(user);
        return Result.success();
    }
}
